<template>
  <el-upload
    class="upload-demo"
    action="/api/testUpload"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :on-success="successRes"
    :before-upload="beforeAvatarUpload"
    multiple
    :limit="3"
    :on-exceed="handleExceed"
    :file-list="fileList">
    <el-button size="small" type="primary">点击上传</el-button>
    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
  </el-upload>
</template>

<script>
export default {
  data() {
    return {
      //文件
      fileList: [],
      //前端验证用于减轻服务器压力
      //图片后缀
      suffixImages: ["png", "jpg", "jpeg"],
      //视频后缀
      suffixVideos: ["mp4", "avi","flv"]
    };
  },
  methods: {
    //文件上传成功时的钩子
    successRes(response, file, fileList) {
      this.$message.success("图片上传成功");
    },
    //上传文件之前的钩子
    beforeAvatarUpload(file) {
      console.log(file.size / 1024 / 1024);
      //存储大小判断
      if (file.size / 1024 / 1024 > 5) {
        this.$message.error("图片或视频最大只能是5MB");
        return false;
      }
      //格式判断
      let fileName = file.name;
      let suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length);
      //对图片的后缀名进行循环格式判断
      for (let i = 0; i < this.suffixImages.length; i++) {
        if (suffix.toLowerCase() == this.suffixImages[i]) {
          return true;
        }
      }
      for (let i = 0; i < this.suffixVideos.length; i++) {
        if (suffix.toLowerCase() == this.suffixVideos[i]) {
          return true;
        }
      }
      this.$message.error(`文件后缀名不合法！\r\n图片格式支持${this.suffixImages}\r\n视频格式支持${this.suffixVideos}`);
      return false;
    },
    //删除
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    //预览
    handlePreview(file) {
      console.log(file);
    },
    //上传个数限制
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    }
  }
}
</script>

<style scoped>

</style>
